package com.musemun.service.function.functionimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.musemun.exception.MyDefineException;
import com.musemun.pojo.Employee;
import com.musemun.pojo.Role;
import com.musemun.pojo.Vo.EmployeeHasRole;
import com.musemun.service.EmployeeService;
import com.musemun.service.RoleService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

public abstract class BaseEmployee {
    @Resource
    EmployeeService employeeService;

    @Resource
    RoleService roleService;

    public Employee insertEmployee(Employee employee){
        employee.setPwd(DigestUtils.md5DigestAsHex(employee.getPwd().getBytes()));
        employeeService.save(employee);
        return employee;
    }
    /**
     *
     *
     * @param id 通过id查询employee是否存在存在则返回employee否在抛出异常
     * @return com.musemun.pojo.Employee
     */
    public Employee queryByIdEmployeeExist(long id){
        Employee employee=employeeService.getById(id);
        if(employee==null){
            throw new MyDefineException(400,"找不到该用户");
        }
        return employee;
    }
    public Employee queryByNameEmployeeExist(String name){
        return employeeService.getOne(new QueryWrapper<Employee>().eq("eName", name));
    }

    public EmployeeHasRole queryEmployeeHasRole(long id){
        Employee employee = queryByIdEmployeeExist(id);
        return new EmployeeHasRole(employee, roleService.getAllRolesByEno(id));
    }

    public Employee updateEmployee(Employee employee){
        String pwd = employee.getPwd();
        if(!StringUtils.isEmpty(pwd)){
            employee.setPwd(DigestUtils.md5DigestAsHex(pwd.getBytes()));
        }
        employeeService.updateById(employee);
        //md5加密
        employee.setPwd(pwd);
        return employee;
    }

    public Employee removeEmployee(long id){
        Employee employee = queryByIdEmployeeExist(id);
        employeeService.removeById(id);
        return employee;
    }

    public abstract EmployeeHasRole queryEmployee(long id);
}
